package com.goldmantis.alitrip.common.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * @Author:Shmily
 * @Description:
 * @Date:Create in 12:25 2017/11/20
 */
@Service
public class RedisService {

    @Autowired(required = false)
    private ShardedJedisPool shardedJedisPool;

    private <T> T execute(Function<T,ShardedJedis> func){
        ShardedJedis shardedJedis=null;
        try {
            //从连接池中获取分片对象
            shardedJedis=shardedJedisPool.getResource();
            return func.callback(shardedJedis);
        }finally {
            if(null!=shardedJedis){
                shardedJedis.close();
            }
        }
    }

    public String set(final String key, final String value){
        return execute(new Function<String, ShardedJedis>() {
            @Override
            public String callback(ShardedJedis shardedJedis) {
                return shardedJedis.set(key,value);
            }
        });
    }

    /**
     *  设置
     * @param key
     * @param value
     * @param seconds 单位为秒
     * @return
     */
    public String set(final String key, final String value,final Integer seconds){
        return execute(new Function<String, ShardedJedis>() {
            @Override
            public String callback(ShardedJedis shardedJedis) {
                String setResult = shardedJedis.set(key, value);
                shardedJedis.expire(key,seconds);
                return setResult;
            }
        });
    }

    public String get(final String key){
        return execute(new Function<String, ShardedJedis>() {
            @Override
            public String callback(ShardedJedis shardedJedis) {
                return shardedJedis.get(key);
            }
        });
    }

    public Long del(final String key){
        return execute(new Function<Long, ShardedJedis>() {
            @Override
            public Long callback(ShardedJedis shardedJedis) {
                return shardedJedis.del(key);
            }
        });
    }

    public Long expire(final String key,final Integer seconds){
        return execute(new Function<Long, ShardedJedis>() {
            @Override
            public Long callback(ShardedJedis shardedJedis) {
                return shardedJedis.expire(key,seconds);
            }
        });
    }


}
